package com.ayuku.retail.business.stock;

import java.util.List;
import java.util.Map;

import com.ayuku.commons.AyukuDB;
import com.ayuku.retail.persistence.model.Stock;

public class StockImpl {
	public static List<Stock> getList(String arg) throws Exception {
		List<Stock> lst = AyukuDB
				.getPersist()
				.readList(
						Stock.class,
						"SELECT * FROM Stock WHERE UCASE(BARCODE) LIKE ucase(?) or ucase(NAME) LIKE ucase(?) or ucase(CATEGORY_CODE) LIKE ucase(?)  or ucase(UNIT) LIKE ucase(?) LIMIT 10000",
						new Object[] { arg, arg, arg, arg});
		System.out.println("jumlah baris: " + lst.size());
		return lst;
	}
	
	public static List<Stock> getListForLookup(String arg) throws Exception {
		List<Stock> lst = AyukuDB
				.getPersist()
				.readList(
						Stock.class,
						"SELECT * FROM Stock WHERE UCASE(BARCODE) LIKE ucase(?) or ucase(NAME) LIKE ucase(?) or ucase(CATEGORY_CODE) LIKE ucase(?)  or SELLING_PRICE LIKE ? or QTY_ON_HAND LIKE ? LIMIT 100",
						new Object[] { arg, arg, arg, arg, arg});
		System.out.println("jumlah baris: " + lst.size());
		return lst;
	}

	public static List<Map<String,Object>> getMapList(String arg) throws Exception {
		List<Map<String,Object>> lst = AyukuDB
				.getPersist()
				.readMapList("SELECT * FROM Stock WHERE UCASE(BARCODE) LIKE ucase(?) or ucase(NAME) LIKE ucase(?) or ucase(CATEGORY_CODE) LIKE ucase(?)  or ucase(UNIT) LIKE ucase(?)",
						new Object[] { arg, arg, arg, arg});
		System.out.println("jumlah baris: " + lst.size());
		return lst;
	}
	
	public static Stock getById(String key) throws Exception {
		Stock obj = (Stock) AyukuDB.getPersist().readByPrimaryKey(
				Stock.class, new Object[] { key });
		return obj;
	}

	public static Stock getByBarcode(String key) throws Exception {
		Stock obj = (Stock) AyukuDB.getPersist().read(
				Stock.class,"select * from stock where barcode=? limit 1", new Object[] { key });
		return obj;
	}
	
	public static int add(Stock obj) throws Exception {
		return AyukuDB.getPersist().insert(obj);
	}

	public static int update(Stock obj) throws Exception {
		return AyukuDB.getPersist().update(obj);
	}

	public static int delete(String key) throws Exception {
		int n = AyukuDB.getPersist().executeUpdate(
				"delete from Stock where idx = ?",
				new Object[] { key.trim() });
		return n;
	}

	public static int delete(List<String> ids) throws Exception {
		int n = 0;
		try {
			AyukuDB.getPersist().setAutoCommit(false);
			for (int j = 0; j < ids.size(); j++) {
				String key = ids.get(j);
				n += delete(key);
			}
			AyukuDB.getPersist().commit();
		} catch (Exception e) {
			e.printStackTrace();
			AyukuDB.getPersist().rollback();
			throw new Exception();
		} finally {
			AyukuDB.getPersist().setAutoCommit(true);
		}
		return n;
	}

}
